/*
 * @Author: GuitarXiaohe && 2205227953@qq.com
 * @Date: 2024-01-17 21:22:34
 * @LastEditors: 18163104359 2205227953@qq.com
 * @LastEditTime: 2024-01-26 17:23:26
 * @FilePath: /umi/src/models/permission.ts
 * @Description: 菜单数据汇总
 * QQ:2205227953,邮箱:2205227953@qq.com
 * Copyright (c) 2024 by GuitarXiaohe, All Rights Reserved.
 */
import { UsergroupDeleteOutlined } from "@ant-design/icons";
import { GetRoutersAPI } from "@/api/common";
import XHicon from "@/components/xh-components/xh-icon/index.jsx";
import { dynamicRoutes } from "../../config/routes/index";
const permission = {
  namespace: "permission",
  state: {
    menuOpenKey: "", // 当前菜单目录选中
    menuKey: "", // 当前菜单选中
    menuList: [], // 菜单数据
    navigationMenu: [], // 底部导航
    siderMenu: [], // 侧边导航
    breadcrumb: [], // 面包屑
  },
  effects: {
    // 1 为顶部导航 2 为侧边栏导航
    *getMenuList({ payload }, { call, put, select }) {
      const { data: result } = yield call(() => GetRoutersAPI());

      yield put({
        // 请求完事之后的调用的reducers方法
        type: "menuAndNavigation",
        payload: {
          menuList: result,
          menuType: payload,
        },
      });
    },
  },
  reducers: {
    // 顶部导航与侧边栏导航处理   1 为顶部导航 2 为侧边栏导航
    menuAndNavigation(state, { payload }) {
      let r = [];
      const sdata = JSON.parse(JSON.stringify(payload.menuList));
      const rdata = JSON.parse(JSON.stringify(payload.menuList));
      const defaultData = JSON.parse(JSON.stringify(payload.menuList));
      const sidebarRoutes = filterAsyncRouter(sdata);
      const rewriteRoutes = filterAsyncRouter(rdata, false, true);
      const defaultRoutes = filterAsyncRouter(defaultData);
      const asyncRoutes = filterDynamicRoutes(dynamicRoutes);
      let navigationMenu = [],
        siderMenu = [];
      // 1 为顶部导航
      if (payload.menuType == "1") {
        r = filterAsyncRouter(payload.menuList, false, true).filter((t) => t.label);
        navigationMenu = defaultRoutes;
      }
      // 2 为侧边栏导航
      if (payload.menuType == "2") {
        r = filterAsyncRouter(payload.menuList, false, true).filter((t) => t.label);
        siderMenu = r;
      }

      return { ...state, siderMenu, navigationMenu };
    },
    // 赋值当前菜单目录选中数据 弃用掉了
    setMenuOpenKey(state, { payload: menuOpenKey }) {
      return { ...state, menuOpenKey: menuOpenKey };
    },
    // 赋值当前菜单选中数据
    setMenuKey(state, { payload: menuKey }) {
      return { ...state, menuKey };
    },
    // 赋值给侧边栏菜单数据
    setSiderMenu(state, { payload: menuList }) {
      const r = filterAsyncRouter(menuList, false, true).filter((t) => t.label);
      return { ...state, menuList: r, siderMenu: r };
    },
    // 赋值给底部菜单数据
    setNavigationMenu(state, { payload: menuList }) {
      return { ...state, navigationMenu: menuList };
    },
  },
  // 订阅 一开始就会被执行
  subscriptions: {
    keyboardWatcher({ dispatch }) {
      dispatch({ type: "add" });
    },
    setup({ dispatch, history }) {
      // 监听路由变化 根据页面地址 触发指定的函数（每次切换路由都会被触发）
    },
  },
};

export default permission;

function filterAsyncRouter(asyncRouterMap, lastRouter, type = false) {
  let r = [];
  asyncRouterMap.forEach((route, ind) => {
    const data = {};
    data.label = route.meta ? (route.meta.title ? route.meta.title : "") : "";
    data.path = route.menuType != "M" ? `/${route.path}` : route.path;
    data.key = route.path.includes("/") ? route.path : "/" + route.path;
    data.icon = route.meta ? (route.meta.icon ? route.meta.icon : "") : "";
    data.activeMenu = route.activeMenu;

    if (type && route.children) {
      data.children = filterChildren(route.children, data);
    }

    // data.icon = <UpOutlined></UpOutlined>;
    if (route.children && route.children.length > 0) {
      data.children = filterAsyncRouter(route.children, route, type);
    }
    // 隐藏菜单
    if (!route.hidden) {
      r.push({
        label: data.label,
        path: data.path,
        key: data.key,
        icon: data.icon ? <XHicon icon={data.icon} /> : "",
        children: data.children,
      });
    }
  });

  return r;
}

function filterChildren(childrenMap, lastRouter = false) {
  var children = [];
  childrenMap.forEach((el, index) => {
    el.icon = el.icon ? <XHicon icon={el.icon} /> : false;
    if (el.children && el.children.length) {
      el.children.forEach((c) => {
        c.path = el.path + "/" + c.path;
        if (c.children && c.children.length) {
          children = children.concat(filterChildren(c.children, c));
        }
        children.push({
          label: c.name,
          key: c.path,
          path: c.path,
          icon: c.icon ? <XHicon icon={c.icon} /> : false,
        });
      });
      return;
    }

    if (lastRouter) {
      el.path = lastRouter.path + "/" + el.path;
    }
    children = children.concat([
      {
        label: el.name,
        key: el.path,
        path: el.path,
        icon: el.icon ? <XHicon icon={el.icon} /> : false,
      },
    ]);
  });
  return children;
}

// 动态路由遍历，验证是否具备权限
export function filterDynamicRoutes(routes) {
  const res = [];
  routes.forEach((route) => {
    if (route.permissions) {
      if (auth.hasPermiOr(route.permissions)) {
        res.push(route);
      }
    } else if (route.roles) {
      if (auth.hasRoleOr(route.roles)) {
        res.push(route);
      }
    }
  });
  return res;
}

export const loadView = (view) => {
  let res;
  for (const path in modules) {
    const dir = path.split("views/")[1].split(".vue")[0];
    if (dir === view) {
      res = () => modules[path]();
    }
  }
  ret;
};
